import 'dart:async';
import 'package:get/get.dart';
import 'package:honeypotflutter/modules/deliver/api/deliver_api.dart';
import 'package:honeypotflutter/modules/deliver/pages/deliver_cancel/view.dart';
import 'package:honeypotflutter/modules/deliver/pages/deliver_select/view.dart';
import 'package:honeypotflutter/public/public_alert.dart';
import '../../model/deliver_result.dart';

class DeliverSuccessLogic extends GetxController {
  Timer? _timer;

  RxString threeTitle = RxString("投递成功");

  DeliverResult? result;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    result = Get.arguments;
    _startTimer();
  }

  /*
  * 开启倒计时
  * */
  _startTimer() async {
    if (_timer != null && _timer!.isActive) {
      return;
    }
    if (_timer != null) {
      _timer?.cancel();
      _timer = null;
    }
    int _time = 30;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_time < 0) {
        sureAction();
        return;
      }
      threeTitle.value = "投递成功(${_time}s)";
      _time -= 1;
    });
  }

  /*
  * 取消
  * */
  cancelAction() async {
    HLAlert.showSureCancelAlert(
        title: "取消投递",
        message: "确定放弃此次投递?",
        sureAction: (bool isOK) async {
          if (isOK) {
            await DeliverApi.sureAction(id: result!.id!, status: 2);
            _timer?.cancel();
            _timer = null;
            Get.to(DeliverCancelPage(), arguments: Get.arguments);
          }
        });
  }

  /*
  * 确认
  * */
  sureAction() async {
    _timer?.cancel();
    _timer = null;
    if (result == null || result!.id == null) {
      return;
    }
    await DeliverApi.sureAction(id: result!.id!, status: 1);
    Get.off(DeliverSelectPage(), arguments: true);
  }
}
